package com.example.a13001.shoppingmalltemplate.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.MainActivity;
import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.application.ShoppingMallTemplateApplication;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.User;
import com.example.a13001.shoppingmalltemplate.mvpview.RegisterView;
import com.example.a13001.shoppingmalltemplate.presenter.RegisterPredenter;
import com.example.a13001.shoppingmalltemplate.utils.CodeUtils;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.btn_register_sendcode)
    Button btnRegisterSendcode;
    @BindView(R.id.btn_register_commit)
    Button btnRegisterCommit;
    @BindView(R.id.et_register_username)
    EditText etRegisterUsername;
    @BindView(R.id.login_phone_et)
    EditText loginPhoneEt;
    @BindView(R.id.et_register_code)
    EditText etRegisterCode;
    @BindView(R.id.et_register_pwd)
    EditText etRegisterPwd;
    @BindView(R.id.login_pw_et)
    EditText loginPwEt;
    @BindView(R.id.tv_register_haveaccount)
    TextView tvRegisterHaveaccount;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    @BindView(R.id.et_register_piccode)
    EditText etRegisterPiccode;
    @BindView(R.id.iv_register_back)
    ImageView ivRegisterBack;
    private TimeCount timeCount;

    private PopupWindow popWnd;
    private String code;
    private String mTimestamp;
    private RegisterPredenter registerPredenter = new RegisterPredenter(RegisterActivity.this);
    private static final String TAG = "RegisterActivity";
    private String mPhoneNumber;
    private String mPicCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);

        registerPredenter.onCreate();
        registerPredenter.attachView(registerView);
        timeCount = new TimeCount(60000, 1000);

        String safetyCode = MyUtils.getMetaValue(RegisterActivity.this, "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        mTimestamp = Utils.getTimeStamp();


        final CodeUtils codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
        ivCode.setImageBitmap(bitmap);
//        GlideUtils.setNetImage(RegisterActivity.this,"https://jiujiukeji002.qkk.cn/ValidateCode.aspx?size=2",ivCode);
        ivCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final CodeUtils codeUtils = CodeUtils.getInstance();
                Bitmap bitmap = codeUtils.createBitmap();
                ivCode.setImageBitmap(bitmap);
//                GlideUtils.setNetImageNoCache(RegisterActivity.this,"https://jiujiukeji002.qkk.cn/ValidateCode.aspx?size=2",ivCode);
            }
        });
    }

    RegisterView registerView = new RegisterView() {
        @Override
        public void onSuccessDoRegister(User user) {
            Log.e(TAG, "onSuccessDoRegister: " + user.toString());
            int status = user.getStatus();
            if (status > 0) {
                String phone = loginPhoneEt.getText().toString().trim();
                String pwd = loginPwEt.getText().toString().trim();
                registerPredenter.doLogin(AppConstants.COMPANY_ID, code, mTimestamp, phone, pwd, AppConstants.FROM_MOBILE);
            } else {
                Toast.makeText(RegisterActivity.this, "" + user.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onSuccessDoLogin(User user) {
            int status = user.getStatus();
            if (status > 0) {
                String phone = loginPhoneEt.getText().toString().trim();
                String pwd = loginPwEt.getText().toString().trim();
                ShoppingMallTemplateApplication.loginType = "phone";
                MyUtils.putSpuString(AppConstants.USER_NAME, phone);
                MyUtils.putSpuString(AppConstants.USER_PWD, pwd);
                MyUtils.putSpuString("logintype", "phone");
                startActivity(new Intent(RegisterActivity.this, MainActivity.class).putExtra("type", "register"));
            } else {

            }
        }

        @Override
        public void onSuccessGetPicCode(CommonResult commonResult) {
            Log.e(TAG, "onSuccessGetPicCode: " + commonResult.toString());
            int status = commonResult.getStatus();
            if (status > 0) {
                mPhoneNumber = loginPhoneEt.getText().toString().trim();
                mPicCode = commonResult.getCode();
                if (TextUtils.isEmpty(mPhoneNumber)) {
                    Toast.makeText(RegisterActivity.this, "请先输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                registerPredenter.getPhoneCode(AppConstants.COMPANY_ID, code, mTimestamp, mPhoneNumber, commonResult.getCode(), AppConstants.FROM_MOBILE);
            } else {
                Toast.makeText(RegisterActivity.this, "" + commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onSuccessGetPhoneCode(CommonResult commonResult) {
            Log.e(TAG, "onSuccessGetPhoneCode: " + commonResult.toString());
            int status = commonResult.getStatus();
            if (status > 0) {
                timeCount.start();
                Toast.makeText(RegisterActivity.this, "发送成功，请查看您的手机短信获取校验码", Toast.LENGTH_SHORT).show();
                /**
                 * 0：发送成功，请查看您的手机短信获取校验码1：发送失败，未输入手机账号
                 2：发送失败，手机账号格式不正确3：发送失败，图形验证码超时
                 4：发送失败，图形验证码不正确5：发送失败，同一手机短信发送太频繁
                 6：发送失败，短信验证未启用7：发送失败，该手机已被使用
                 */
                int cnktype = commonResult.getChkType();

            } else {
                Toast.makeText(RegisterActivity.this, "" + commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError: " + result.toString());
        }
    };

    @Override
    protected void onStop() {
        super.onStop();

    }

    @OnClick({R.id.iv_register_back,R.id.btn_register_sendcode, R.id.btn_register_commit, R.id.tv_register_haveaccount})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_register_back:
                onBackPressed();
                break;
            //获取验证码
            case R.id.btn_register_sendcode:
//                showPopUpWindow();

                registerPredenter.getPicCode(AppConstants.COMPANY_ID, code, mTimestamp);
//                timeCount.start();
                break;
            //注册
            case R.id.btn_register_commit:
                String phone = loginPhoneEt.getText().toString().trim();
                String pwd = etRegisterPwd.getText().toString().trim();
                String pwds = loginPwEt.getText().toString().trim();
                String phonecode = etRegisterCode.getText().toString().trim();
                String piccode = CodeUtils.getInstance().getCode();
                String piccode1 = etRegisterPiccode.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(phonecode)) {
                    Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(pwd)) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(pwds)) {
                    Toast.makeText(this, "请输入确认密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(piccode1)) {
                    Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!piccode.equalsIgnoreCase(piccode1)) {
                    Toast.makeText(this, "图形验证码错误，请重新输入", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String, String> map = new HashMap<>();
                map.put("type", AppConstants.USER_PHONE);
                map.put("account", phone);
                map.put("pwd", pwd);
                map.put("pwds", pwds);
                map.put("txcode", mPicCode);
                map.put("code", phonecode);
                map.put("from", AppConstants.FROM_MOBILE);
                map.put("appos", AppConstants.androidos);
                map.put("appkey",MyUtils.getImei());
                Log.e(TAG, "onViewClicked: " + map.toString());
                registerPredenter.doRegister(AppConstants.COMPANY_ID, this.code, mTimestamp, map);
                break;
            //已有账号
            case R.id.tv_register_haveaccount:
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                break;
        }
    }

    /**
     * 倒计时类
     */
    class TimeCount extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // mBtnGetcode.setBackgroundColor(Color.parseColor("#B6B6D8"));
            btnRegisterSendcode.setClickable(false);
            btnRegisterSendcode.setText("" + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
            btnRegisterSendcode.setText("获取验证码");
            btnRegisterSendcode.setClickable(true);
            //  mBtnGetcode.setBackgroundColor(Color.parseColor("#4EB84A"));
        }
    }


    private void showPopUpWindow() {
        View contentView = LayoutInflater.from(RegisterActivity.this).inflate(R.layout.item_yzcode, null);
        popWnd = new PopupWindow(RegisterActivity.this);
        popWnd.setContentView(contentView);
//    popWnd.setWidth(263);
//    popWnd.setHeight(320);
        popWnd.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        View contentView1 = popWnd.getContentView();
        final ImageView mIvCode = (ImageView) contentView1.findViewById(R.id.iv_code);
        final EditText mEtCode = (EditText) contentView1.findViewById(R.id.et_code);
        Button mBtnSure = (Button) contentView1.findViewById(R.id.btn_sure);
        final CodeUtils codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
        mIvCode.setImageBitmap(bitmap);
//        GlideUtils.setNetImage(RegisterActivity.this,"https://jiujiukeji002.qkk.cn/ValidateCode.aspx?size=2",mIvCode);
        mIvCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final CodeUtils codeUtils = CodeUtils.getInstance();
                Bitmap bitmap = codeUtils.createBitmap();
                mIvCode.setImageBitmap(bitmap);
//                GlideUtils.setNetImageNoCache(RegisterActivity.this,"https://jiujiukeji002.qkk.cn/ValidateCode.aspx?size=2",mIvCode);
            }
        });
        mBtnSure.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View view) {
                String codeStr = mEtCode.getText().toString().trim();
                Log.e("codeStr", codeStr);
                if (null == codeStr || TextUtils.isEmpty(codeStr)) {
                    Toast.makeText(RegisterActivity.this, "请输入验证码", 0).show();
                    return;
                }
                String code = codeUtils.getCode();
                Log.e("code", code);
                if (code.equalsIgnoreCase(codeStr)) {
                    Toast.makeText(RegisterActivity.this, "验证码正确", 0).show();
                } else {
                    Toast.makeText(RegisterActivity.this, "验证码错误", 0).show();
                }
            }
        });
        popWnd.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE && !popWnd.isFocusable()) {
                    //如果焦点不在popupWindow上，且点击了外面，不再往下dispatch事件：
                    //不做任何响应,不 dismiss popupWindow
                    return true;
                }
                return false;
            }
        });
        popWnd.setTouchable(true);
        popWnd.setFocusable(false);
        popWnd.setOutsideTouchable(false);
//        popWnd.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        backgroundAlpha(0.6f);

        //添加pop窗口关闭事件
        popWnd.setOnDismissListener(new poponDismissListener());

        popWnd.setTouchInterceptor(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    popWnd.dismiss();
                    return true;
                }
                return false;
            }
        });

        //popWnd.showAsDropDown(mTvLine, 200, 0);
        popWnd.showAtLocation(RegisterActivity.this.findViewById(R.id.btn_register_sendcode),
                Gravity.CENTER, 0, 0);

    }

    /**
     * 添加弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     *
     * @author cg
     */
    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
        }

    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
}
